<template>
  <div class="detail-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>{{ detail.type === 0 ? '失物' : '招领' }}信息详情</span>
          <el-tag :type="detail.type === 0 ? 'warning' : 'success'">
            {{ detail.type === 0 ? '失物' : '招领' }}
          </el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border v-if="detail.id">
        <el-descriptions-item label="信息编号">{{ detail.infoNo }}</el-descriptions-item>
        <el-descriptions-item label="物品名称">{{ detail.itemName }}</el-descriptions-item>
        <el-descriptions-item label="物品类别">{{ getCategoryName(detail.category) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detail.status)">
            {{ getStatusName(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="物品特征" :span="2">{{ detail.description }}</el-descriptions-item>
        <el-descriptions-item :label="detail.type === 0 ? '丢失日期' : '拾到日期'">
          {{ formatDate(detail.lostDate) }}
        </el-descriptions-item>
        <el-descriptions-item :label="detail.type === 0 ? '丢失时段' : '拾到时段'">
          {{ detail.lostTime }}
        </el-descriptions-item>
        <el-descriptions-item label="校园区域">{{ detail.locationArea }}</el-descriptions-item>
        <el-descriptions-item label="具体位置">{{ detail.locationDetail }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ maskPhone(detail.contactPhone) }}</el-descriptions-item>
        <el-descriptions-item label="备用联系方式" v-if="detail.contactBackup">
          {{ detail.contactBackup }}
        </el-descriptions-item>
        <el-descriptions-item label="物品存放地点" :span="2" v-if="detail.storageLocation">
          {{ detail.storageLocation }}
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatDateTime(detail.createTime) }}</el-descriptions-item>
      </el-descriptions>

      <div class="actions" v-if="detail.status === 1">
        <el-button type="primary" @click="showClaimDialog" v-if="userStore.isLoggedIn">
          申请认领
        </el-button>
        <el-button type="primary" @click="$router.push('/login')" v-else>
          登录后认领
        </el-button>
      </div>
    </el-card>

    <!-- 认领申请对话框 -->
    <el-dialog v-model="claimDialogVisible" title="申请认领" width="600px">
      <el-form :model="claimForm" :rules="claimRules" ref="claimFormRef" label-width="120px">
        <el-form-item label="申请人姓名" prop="applicantName">
          <el-input v-model="claimForm.applicantName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="学号/工号" prop="applicantStudentNo">
          <el-input v-model="claimForm.applicantStudentNo" placeholder="请输入学号或工号" />
        </el-form-item>
        <el-form-item label="认领理由" prop="claimReason">
          <el-input 
            v-model="claimForm.claimReason" 
            type="textarea" 
            :rows="4"
            placeholder="请说明认领理由，包含至少一个独有特征（5-10000字）"
            maxlength="10000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="claimDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitClaim" :loading="submitting">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getItemDetail } from '@/api/item'
import { submitClaim } from '@/api/claim'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const detail = ref({})
const claimDialogVisible = ref(false)
const claimFormRef = ref(null)
const submitting = ref(false)

const claimForm = reactive({
  itemInfoId: null,
  applicantName: '',
  applicantStudentNo: '',
  claimReason: ''
})

const claimRules = {
  applicantName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  applicantStudentNo: [{ required: true, message: '请输入学号/工号', trigger: 'blur' }],
  claimReason: [
    { required: true, message: '请输入认领理由', trigger: 'blur' },
    { min: 5, max: 10000, message: '认领理由长度为5-10000字', trigger: 'blur' }
  ]
}

const categoryNames = ['电子设备', '证件卡类', '学习用品', '生活用品', '衣物鞋帽', '其他']
const statusNames = ['待审核', '已发布', '已认领', '已失效', '审核驳回']

const getCategoryName = (category) => categoryNames[category] || '未知'
const getStatusName = (status) => statusNames[status] || '未知'

const getStatusType = (status) => {
  const types = ['info', 'success', 'success', 'info', 'danger']
  return types[status] || 'info'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString()
}

const maskPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

const showClaimDialog = () => {
  claimForm.itemInfoId = detail.value.id
  claimDialogVisible.value = true
}

const handleSubmitClaim = () => {
  claimFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await submitClaim(claimForm)
        ElMessage.success('提交成功，等待审核')
        claimDialogVisible.value = false
        router.push('/my-claims')
      } catch (error) {
        console.error(error)
      } finally {
        submitting.value = false
      }
    }
  })
}

const loadDetail = async () => {
  loading.value = true
  try {
    const res = await getItemDetail(route.params.id)
    detail.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadDetail()
})
</script>

<style scoped>
.detail-container {
  max-width: 900px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.actions {
  margin-top: 30px;
  text-align: center;
}
</style>

